package com.ruoyi.cms.blog.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.ruoyi.cms.blog.domain.CmsCity;
import com.ruoyi.cms.blog.domain.vo.CmsCityVO;
import com.ruoyi.cms.blog.mapper.CmsCityMapper;
import com.ruoyi.cms.blog.service.ICmsCityService;
import com.ruoyi.common.core.domain.AjaxResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class CmsCityServiceImpl implements ICmsCityService {

    private final CmsCityMapper cmsCityMapper;

    @Override
    public AjaxResult select(CmsCity city) {
        List<CmsCity> lists = cmsCityMapper.select(city);
        List<CmsCityVO> ccs = new ArrayList<>(16);
        if (!lists.isEmpty()) {
            lists.stream()
                    .collect(Collectors.groupingBy(CmsCity::getZhouName))
                    .forEach((key, value) -> {
                        CmsCityVO vo = new CmsCityVO();
                        List<CmsCityVO.City> cityNames = vo.getCityNames();
                        vo.setZhouName(key);
                        if (!value.isEmpty()) {
                            value.forEach(v -> {
                                CmsCityVO.City cc = new CmsCityVO.City();
                                cc.setId(v.getId()).setName(v.getName());
                                cityNames.add(cc);
                            });
                        }
                        ccs.add(vo);
                    });
        }
        return AjaxResult.success(ccs);
    }

    @Override
    public AjaxResult select2(CmsCity city) {
        List<CmsCity> lists = cmsCityMapper.select(city);
        return AjaxResult.success(lists);
    }

    @Override
    public AjaxResult select3() {
        List<CmsCity> lists = cmsCityMapper.select3();
        return AjaxResult.success(lists);
    }

    @Override
    public AjaxResult insert(CmsCity city) {
        log.info("新增入参 {}", JSONUtils.toJSONString(city));
        CmsCity one = cmsCityMapper.getOne(city);
        return Optional.ofNullable(one)
                .map(o -> AjaxResult.error("The city already exists"))
                .orElse(AjaxResult.success(cmsCityMapper.insert(city)));
    }

    @Override
    public AjaxResult update(CmsCity city) {
        CmsCity one = cmsCityMapper.getOne(city);
        return Optional.ofNullable(one.getName())
                .map(o -> AjaxResult.error())
                .orElse(AjaxResult.success(cmsCityMapper.update(city)));
    }

    @Override
    public AjaxResult delete(Long id) {
        int count = cmsCityMapper.selectChild(id);
        if (count > 0) {
            return AjaxResult.error("Please delete the subset first");
        }
        return AjaxResult.success(cmsCityMapper.delete(id));
    }
}
